/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.airlogger.log.control
{
	import com.bourre.commands.AbstractCommand;
	import flash.events.Event;
	import com.airlogger.event.AirLoggerLogEvent;
	import com.airlogger.log.model.UIModel;
	import com.airlogger.log.model.AirLoggerModelList;
	import com.airlogger.log.AirLoggerLogPlugin;
	import com.airlogger.event.SWFEvent;
	import com.bourre.log.PixlibDebug;
	import com.airlogger.log.model.LogModel;
	import com.airlogger.log.model.SWFData;

	public class DisconnectSWF extends AbstractCommand
	{
		override public function execute(e:Event=null):void
		{
			var evt : SWFEvent = e as SWFEvent;
			
			//getLogger().debug( "in DisconnectSWF.execute " + evt + ", " + evt.id );
			
			var model : LogModel = getOwner().getModelLocator().getModel( evt.id) as LogModel;
			
			//getLogger().debug( model );
			model.release();
			
			var uimodel : UIModel = getOwner().getModelLocator().getModel( AirLoggerModelList.UI ) as UIModel;
			
			uimodel.removeSWF( evt.id );
			uimodel.fireOnSWFRemovedEvent( evt.id );
			
			//getLogger().debug( "in DisconnectSWF.execute focus : " + uimodel.getFocus() );

			try
			{
				(getOwner() as AirLoggerLogPlugin).fireOnDeconnectionEvent( evt.id );
				
				if( evt.id == uimodel.getFocus() )
				{
					var swfs : Array = uimodel.getSWFs();
					if( swfs.length != 0 )
					{
						uimodel.setFocus( (swfs[ 0 ] as SWFData).id );
					}
					uimodel.fireOnRefreshEvent();
				}
			}
			catch( e : Error )
			{
				getLogger().error( e + "\n" + e.getStackTrace() );
			}
			
			
		}
	}
}